package beautiful.butterfly.distributed_task_processing_engine.task_manage.task_processor;

import beautiful.butterfly.distributed_task_processing_engine.cron_expression.CronExpression;
import beautiful.butterfly.distributed_task_processing_engine.tools.DateFormats;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Timer;

@Slf4j
class PauseOrResumeTimerTask extends java.util.TimerTask
{
    public static int type_pause = 1;
    public static int type_resume = 2;

    TaskProcessor taskProcessor;
    Timer timer;
    int type;
    String cronExpression;

    public PauseOrResumeTimerTask(TaskProcessor taskProcessor, Timer timer, int type, String cronExpression)
    {
        this.taskProcessor = taskProcessor;
        this.timer = timer;
        this.type = type;
        this.cronExpression = cronExpression;
    }

    public void run()
    {
        try
        {
            Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
            this.cancel();//取消调度任务
            Date nowDate = new Date(System.currentTimeMillis());
            CronExpression cronExpression = new CronExpression(this.cronExpression);
            Date nextDateTime = cronExpression.getNextTimeAfter(nowDate);
            if (this.type == type_resume)
            {
                taskProcessor.resume();//到达开始时间,resume调度
                this.taskProcessor.getTaskProcessorInfo().setNextRunStartTime(DateFormats.transferDataToString(nextDateTime));
            } else
            {
                taskProcessor.pause();//到达终止时间,pause调度
                this.taskProcessor.getTaskProcessorInfo().setNextRunEndTime(DateFormats.transferDataToString(nextDateTime));
            }
            this.timer.schedule(new PauseOrResumeTimerTask(this.taskProcessor, this.timer, this.type, this.cronExpression), nextDateTime);
        } catch (Throwable ex)
        {
            log.error(ex.getMessage(), ex);
        }
    }
}
